<?php
/**
 * TinyCatPHP 极简、快速、创新、易用、高性能的PHP应用开发框架
 * User: CnTaiGe <hst042@163.com>
 * Date: 2017/12/3
 */

namespace TinyCatPHP\libs\utils;
class UploadFile
{
    protected $_config;

    public function __construct($config = [])
    {
        $this->_config = array_merge([
            'size' => 0,//默认可上传文件大小
            'allows' => ['jpeg', 'png', 'bmp'],
            'path' => './upload/' . date('Y_m_d') //默认上传目录
        ], $config);
        if (!is_array($this->_config['allows'])) {
            $this->_config['allows'] = explode(',', $this->_config['allows']);
        }
    }

    /**
     * 只支持单文件上传
     * @param string $path 上传路径
     * @return array
     */
    public function upload($path = '')
    {
        $files = current($_FILES);
        $pathinfo = pathinfo($files['name']);
        if (!in_array(strtolower($pathinfo['extension']), $this->_config['allows'])) {
            return ['error' => -1, 'msg' => '不允许上传此 ' . $pathinfo['extension'] . ' 文件类型'];
        }
        if (($this->_config['size'] !== 0) && $this->_config['size'] < $files['size']) {
            return ['error' => -2, 'msg' => '此文件大于最大可上传大小限制,当前文件大小 ' . $files['size']];
        }
        if (empty($path)) {
            $path = $this->_config['path'];
        }
        $fileName = $path . '/' . hash_file('md5', $files['tmp_name']) . '.' . $pathinfo['extension'];
        File::mkdir($fileName);
        if (move_uploaded_file($files['tmp_name'], $fileName)) {
            return [
                'error' => 0,
                'file' => $fileName,
                'upload_file_name' => $pathinfo['basename'],
                'msg' => '上传成功'
            ];
        }
        return ['error' => 1, 'msg' => '上传失败，请重新上传'];
    }
}